#coding=utf-8
import datetime
import time
import collections
import logging
from main import models
from django.db.models import Q
#from itertools import chain

logger = logging.getLogger('main')

def menu_struct(menulist):
    subordinate_dict = collections.defaultdict(list)
    for s in menulist:
        subordinate_dict[s.parent_id].append(s)

    menu_toplist = subordinate_dict.get(0, [])
    
    return_data = []
    
    for menu in menu_toplist:
        menu_top = {}
        menu_top["id"] = menu.id
        menu_top["name"] = menu.name
        menu_top["icon"] = menu.icon
        
        menu_seclist = subordinate_dict.get(menu.id, [])
        
        menu_data = []
        for menu_sec in menu_seclist:
            adv_mess = {}
            adv_mess["id"] = menu_sec.id
            adv_mess["name"] = menu_sec.name
            adv_mess["url"] = menu_sec.url
            menu_data.append(adv_mess)
        menu_top["menu_sec"] = menu_data
        return_data.append(menu_top)
    return return_data
    
def list_to_pagelist(data_list,pagenum,pagecount):
    if pagenum == None or pagenum=="" or pagenum == '0' or int(pagenum) == 0:
        pagenum = 1
    if pagecount ==None or pagecount == "" or pagecount == '0' or int(pagecount) == 0:
        pagecount = 10 
    pagecount = int(pagecount)
    pagesum = data_list.count()
   
    numpage = pagesum/pagecount
    if pagesum%pagecount != 0:
        numpage=numpage+1
        
    pagenum = int(pagenum)
    stateNum = (pagenum-1)*pagecount
    endNum = pagenum*pagecount
    
    logger.info("get_case_batch_data %s:%s",stateNum,endNum)
    data_list = data_list[stateNum:endNum]
    
    page = {}
      #页码
    page["pagenum"] = pagenum
       #每页数据量
    page["pagecount"] = pagecount
      #数据条数
    page["pagesum"] = pagesum
      #总页数
    page["numpage"] = numpage
    return data_list,page